/*
 * OpenlsServlet.java
 *
 * Created on February 11, 2004, 1:54 PM
 */

package com.autolinq.servlet;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;

import org.apache.commons.pool.impl.StackObjectPool;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import com.autolinq.pojo.WeChatMessage;
import com.autolinq.util.http.HttpClientConnectionManager;


/**
 *
 * @author  Patty Zhang
 */
public abstract class AbstractDPCAServlet extends javax.servlet.http.HttpServlet{
    protected final Logger logger = Logger.getLogger(this.getClass().getName());
    protected static final Logger SERVLET_STDOUT = Logger.getLogger("SERVLET_STDOUT");
    protected static final Logger XML_LOG = Logger.getLogger("XML_LOG"); //only enable this Logger when debugging. It's a performance hit to log all the XML.
    protected static final Logger POOL_LOG = Logger.getLogger("POOL_LOG");    
    protected boolean supportsGzip =false;
    
    public Properties prop = new Properties();// 属性集合对象
    private String classpath = this.getClass().getResource("/").getPath();
    
    //http客户端    
    public static DefaultHttpClient httpclient;  
      
    static {    
        httpclient = new DefaultHttpClient();    
        httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端  
        
    }  

    
    /** Creates a new instance of OpenlsServlet */
    public AbstractDPCAServlet() {
        //initMarshalling();
    }
 
    public synchronized void init() throws ServletException{
    	logger.debug("init");                
		try {
			FileInputStream fis = new FileInputStream(classpath
					+ "/prop.properties");// 属性文件输入流
			prop.load(fis);// 将属性文件流装载到Properties对象中
			fis.close();// 关闭流
		} catch (Exception ex) {
			ex.printStackTrace();
		}
    }
    
    
    //all properties for the OpenlsServiceFactory can be
    //set in web.xml
    protected Properties getServiceFactoryProperties(){
        //first look for global context parameters
        //then override with individual init params in servlets
        
        ServletContext context = getServletContext();
        Enumeration _enum = context.getInitParameterNames();
        Properties p = new Properties();
        while(_enum.hasMoreElements()){
            String param = (String) _enum.nextElement();
                p.setProperty(param,  context.getInitParameter(param));
        }
        
        //then override context parameters with individual init params in servlets
        _enum = getInitParameterNames();
        while(_enum.hasMoreElements()){
            String param = (String) _enum.nextElement();
                p.setProperty(param,  getInitParameter(param));
        }
        logger.debug(p);
        return p;
    }
    
    public void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws javax.servlet.ServletException, java.io.IOException {
    	logger.debug("service");  
    }

    protected WeChatMessage unmarshalFromStream(InputStream is) throws Exception{        
    	WeChatMessage message = new WeChatMessage();
    	try {
			System.out.println("date:"+new Date());

			SAXBuilder sax = new SAXBuilder();

			Document doc = sax.build(is);
			Element root = doc.getRootElement();
			List list = root.getChildren();
			for (int j = 0; j < list.size(); j++) {
				Element first = (Element) list.get(j);

				if (first.getName().equals("ToUserName")) {
					message.setToUserName(first.getValue().trim());
					System.out.println("toName:"+message.getToUserName());
					logger.debug("toName:"+message.getToUserName());
				} else if (first.getName().equals("FromUserName")) {
					message.setFromUserName(first.getValue().trim());
					logger.debug("fromName:"+message.getFromUserName());
					System.out.println("fromName:"+message.getFromUserName());
				} else if (first.getName().equals("MsgType")) {
					message.setMsgType(first.getValue().trim());
					logger.debug("MsgType:"+message.getMsgType());
					System.out.println("MsgType:"+message.getMsgType());
				} else if (first.getName().equals("Content")) {
					message.setContent(first.getValue().trim());
					logger.debug("Content:"+message.getContent());
					System.out.println("Content:"+message.getContent());
				} else if (first.getName().equals("Event")) {
					message.setEvent(first.getValue().trim());
					logger.debug("Event:"+message.getEvent());
					System.out.println("Event:"+message.getEvent());
				} else if (first.getName().equals("EventKey")) {
					message.setEventKey(first.getValue().trim());
					logger.debug("EventKey:"+message.getEventKey());
					System.out.println("EventKey:"+message.getEventKey());
				}else if (first.getName().equals("DeviceType")) {
					message.setDeviceType(first.getValue().trim());
				} else if (first.getName().equals("SessionID")) {
					message.setSessionID(first.getValue().trim());
					System.out.println("SessionID:"+message.getSessionID());
				} else if (first.getName().equals("DeviceID")) {
					message.setDeviceID(first.getValue().trim());
					logger.debug("DeviceID:"+message.getDeviceID());
					System.out.println("DeviceID:"+message.getDeviceID());
				}  else if (first.getName().equals("OpenID")) {
					message.setOpenID(first.getValue().trim());
					logger.debug("OpenID:"+message.getOpenID());
					System.out.println("OpenID:"+message.getOpenID());
				} else if (first.getName().equals("MsgID")) {
					message.setMsgID(first.getValue().trim());
					logger.debug("MsgID:"+message.getMsgID());
					System.out.println("MsgID:"+message.getMsgID());
				}else if (first.getName().equals("CreateTime")) {
					message.setCreateTime(first.getValue().trim());
					logger.debug("CreateTime:"+message.getCreateTime());
					System.out.println("CreateTime:"+message.getCreateTime());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
    	return message;
    }
    
    protected String unmarshalFromJSONStream(InputStream is) throws Exception{        
    	String lineResp = "";
    	try {
			System.out.println("date:"+new Date());

			BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));  
            String line = "";  
            
            for (line = br.readLine(); line != null; line = br.readLine()) {  
                System.out.println(line);  
                lineResp += line;
            }  

		} catch (Exception e) {
			e.printStackTrace();
		}
    	return lineResp;
    }
}


